package com.navinfo.platform.trip.common.arithmetic;

import com.navinfo.platform.trip.common.arithmetic.data.CommonData;
import com.navinfo.platform.trip.common.arithmetic.data.OuterStatisticData;
import com.navinfo.platform.trip.common.arithmetic.enums.EventStatus;
import com.navinfo.platform.trip.common.arithmetic.enums.EventType;
import com.navinfo.platform.trip.common.arithmetic.manager.AbstractArithmetic;
import com.navinfo.platform.trip.common.arithmetic.manager.EventConvert;
import com.navinfo.platform.trip.common.arithmetic.var.VarCoastInGear;
import com.navinfo.platform.trip.common.config.ConfigMap;
import com.navinfo.platform.trip.common.util.ArithmeticUtils;

import java.util.Optional;

/**
 * 在档滑行算法<br/>
 * 依赖{@link Mileage}里程油耗算法<br/>
 * 输出：统计、事件<br/>
 */
public class CoastInGear extends AbstractArithmetic<VarCoastInGear> {
    /**
     * 事件类型
     */
    private static final EventType EVENT_TYPE = EventType.paringRangeSlide;
    /**
     * 时长阀值 单位：ms
     */
    private int timeThreshold =  ConfigMap.getInteger("GearSlide_Time_Threshold");
    /**
     * 速度阀值 单位：km/h
     */
    private int speedThreshold = ConfigMap.getInteger("GearSlide_Speed_Threshold");
    /**
     *  转数阀值 单位：RPM
     */
    private int rotationThreshold = ConfigMap.getInteger("GearSlide_Rotation_Threshold");

    /**
     * 判断当前点是否为在档滑行状态
     * 在档滑行状态判定:速度>30km/h,发动机转速>=800rpm，不踩油门，燃油消耗率为0】
     */
    public boolean isCurrentGearSlide() {
        CommonData data = getCommonData();
        return data.getSpeedKmh()>speedThreshold  && data.getRotation()>=rotationThreshold && data.getAcceleratorPosition()==0.00;
    }

    @Override
    public void calculate() {
        logger.debug("进入在档滑行算法.[terminalId:{}]", terminalId);
        VarCoastInGear var = getObj();

        boolean previousIdle = var.isPreGearSlide();
        boolean currentIdle = isCurrentGearSlide();
        var.setPreGearSlide(currentIdle);
        logger.debug("在档滑行算法，在档滑行状态：上次:{},本次:{}.[terminalId:{}]", previousIdle, currentIdle, terminalId);

        switch (getEventStatus(previousIdle, currentIdle)) {
            case START:
                logger.debug("在档滑行算法，事件开始.[terminalId:{}]", terminalId);
                startEventData(EVENT_TYPE);
                break;
            case IN:
                logger.debug("在档滑行算法，事件中.[terminalId:{}]", terminalId);
                calcEventData(EVENT_TYPE);
                break;
            case END:
                logger.debug("在档滑行算法，事件结束.[terminalId:{}]", terminalId);
                calcEventData(EVENT_TYPE);
                endEvent();
                break;
            default:
                logger.debug("在档滑行算法，在档滑行状态：上一次和本次都未在档滑行，跳出算法.[terminalId:{}]", terminalId);
                break;
        }

        //行程结束时要清理对应的未结束事件
        if (getCommonData().isTripLastNode()) {
            endEvent();
        }
        logger.debug("在档滑行算法结束.[terminalId:{}]", terminalId);
    }

    @Override
    public void collect(OuterStatisticData statisticDataOut) {
        VarCoastInGear var = getObj();
        statisticDataOut.setInGearCoastNumber(var.getNumber());
        statisticDataOut.setInGearCoastMileage(ArithmeticUtils.mileageMToM(var.getMileage()));
        statisticDataOut.setInGearCoastDuration(ArithmeticUtils.timeMsToSecond(var.getDuration()));
    }

    /**
     * 累加事件信息
     */
    @Override
    public void calcEventData(EventType eventType) {
        Optional.ofNullable(drivingData.getEventData(eventType)).ifPresent(eventData -> {
            EventConvert.convertCommonField(eventData, drivingData);
            if (getCommonData().getGpsTime()-eventData.getStartGpsTime() >= timeThreshold) {
                // 满足时长阈值后，设置事件的结束状态
                eventData.setStatus(EventStatus.END.getValue());
            }
        });
    }

    /**
     * 处理事件的结束状态
     */
    private void endEvent() {
        Optional.ofNullable(drivingData.getEventData(EVENT_TYPE)).ifPresent(eventData -> {
            EventConvert.convertEnd(eventData, drivingData);
            drivingData.removeEventData(EVENT_TYPE);

            if (Optional.ofNullable(eventData.getDuration()).orElse(0L) >= timeThreshold) {
                logger.debug("在档滑行时间{}ms,进行统计", Optional.ofNullable(eventData.getDuration()).orElse(0L));

                //复制事件到统计变量中
                VarCoastInGear var = getObj();
                var.addNumber(1);
                var.addMileage(Optional.ofNullable(eventData.getExtendField05()).orElse(0.0));
                var.addFuel(Optional.ofNullable(eventData.getExtendField06()).orElse(0.0));
                var.addDuration( Optional.ofNullable(eventData.getDuration()).orElse(0L).intValue());

                drivingData.addEventDataToList(eventData);
            } else {
                logger.debug("在档滑行时间{}ms,小于阈值{}ms，不进行统计", Optional.ofNullable(eventData.getDuration()).orElse(0L), timeThreshold);
            }
        });
    }
}
